package com.sun.lg.factory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlBeanFactory {

    private static Map<String, Object> map = new HashMap<>();

    static {

        InputStream resourceAsStream = XmlBeanFactory.class.getClassLoader().getResourceAsStream("beans.xml");

        try {
            Document read = new SAXReader().read(resourceAsStream);
            Element rootElement = read.getRootElement();
            List<Element> list = rootElement.selectNodes("//bean");
            for (Element element : list) {
                String id = element.attributeValue("id");
                String javaBean = element.attributeValue("class");
                Class<?> aClass = Class.forName(javaBean);
                Object o = aClass.newInstance();
                map.put(id, o);
            }

            List<Element> list1 = rootElement.selectNodes("//property");
            for (Element element : list1) {
                String name = element.attributeValue("name");
                String ref = element.attributeValue("ref");

                Element parent = element.getParent();
                String id = parent.attributeValue("id");
                Object parentObj = map.get(id);
                Method[] methods = parentObj.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getName().equalsIgnoreCase("set" + name)) {
                        method.invoke(parentObj, map.get(ref));
                    }
                }
            }
        } catch (DocumentException | InvocationTargetException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static Object getBean(String name) {
        Object o = map.get(name);
        return o;
    }

}
